package cn.itsource.user.controller;

import cn.itsource.user.service.IUserService;
import cn.itsource.user.domain.User;
import cn.itsource.user.query.UserQuery;
import cn.itsource.utills.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if( user.getId()!=null)
                userService.update(user);
            else
                userService.add(user);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setSuccess(false).setMsg("保存对象失败！"+e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
                userService.delete(id);
            return  AjaxResult.success().setSuccess(true).setMsg("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error().setSuccess(false).setMsg("操作失败");
    }
	
    //获取用户
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id")Long id)
    {
        try {
            User findnoe = userService.findnoe(id);
            return AjaxResult.success().setData(findnoe);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<User> list(){

        return userService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public AjaxResult findQuey(@RequestBody UserQuery query)
    {
        try {
            List<User> queryData = userService.queryData(query);
            Long count = userService.queryCount(query);
            return AjaxResult.success().setData(queryData).setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }
}
